import axios from 'axios'
import store from '../store'
import { ElMessage } from 'element-plus'
import requestCache from '../utils/requestCache'
import performanceMonitor from '../utils/performanceMonitor'
import logger from '../utils/logger'

// 安全使用logger（防止logger未定义）
const safeLogger = {
  error: (message, ...args) => {
    if (logger && logger.error) {
      logger.error(message, ...args)
    }
  },
  warn: (message, ...args) => {
    if (logger && logger.warn) {
      logger.warn(message, ...args)
    }
  },
  log: (message, ...args) => {
    if (logger && logger.log) {
      logger.log(message, ...args)
    }
  },
  info: (message, ...args) => {
    if (logger && logger.info) {
      logger.info(message, ...args)
    }
  },
  debug: (message, ...args) => {
    if (logger && logger.debug) {
      logger.debug(message, ...args)
    }
  }
}

// 自动检测API基础URL
const getApiBaseUrl = () => {
  // 如果环境变量已设置，直接使用
  if (process.env.VUE_APP_API_BASE_URL) {
    return process.env.VUE_APP_API_BASE_URL
  }
  
  // 开发环境：自动检测当前主机地址（仅在浏览器环境中）
  if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined' && window.location) {
    const hostname = window.location.hostname
    const protocol = window.location.protocol
    // 如果是内网IP或域名，使用当前主机地址
    if (hostname !== 'localhost' && hostname !== '127.0.0.1') {
      return `${protocol}//${hostname}:8000`
    }
  }
  
  // 默认使用localhost（仅用于本地开发）
  return 'http://localhost:8000'
}

// 延迟获取API基础URL，确保在浏览器环境中执行
let API_BASE_URL = 'http://localhost:8000'
if (typeof window !== 'undefined') {
  API_BASE_URL = getApiBaseUrl()
} else {
  // Node.js环境（构建时），使用环境变量或默认值
  API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'
}

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 增加到30秒，适应路线规划等耗时操作
  headers: {
    'Content-Type': 'application/json'
  }
})

// 需要缓存的请求方法（GET请求默认缓存）
const CACHEABLE_METHODS = ['get']
// 不需要缓存的URL模式
const NO_CACHE_PATTERNS = [
  '/auth/login',
  '/auth/register',
  '/routes/plan', // 路线规划不缓存，因为参数复杂且结果可能变化
  '/routes/history' // 历史记录不缓存，需要实时数据
]

// 重试配置
const MAX_RETRIES = 3
const RETRY_DELAY = 1000 // 1秒

// 判断是否应该重试的错误
const shouldRetry = (error) => {
  if (!error.response) {
    // 网络错误，可以重试
    return true
  }
  const status = error.response.status
  // 5xx服务器错误或408超时，可以重试
  return status >= 500 || status === 408 || status === 429
}

// 延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 添加Token到请求头（仅在浏览器环境中）
    if (typeof window !== 'undefined' && window.localStorage) {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Token ${token}`
      }
    }
    
    // 添加请求时间戳，用于调试
    config.metadata = { startTime: new Date() }
    
    // 检查是否需要使用缓存（仅GET请求）
    if (CACHEABLE_METHODS.includes(config.method.toLowerCase())) {
      const shouldCache = !NO_CACHE_PATTERNS.some(pattern => 
        config.url.includes(pattern)
      )
      
      if (shouldCache) {
        const cacheKey = requestCache.generateKey(config.url, config.params)
        const cachedData = requestCache.get(cacheKey)
        
        if (cachedData) {
          // 标记为缓存响应
          config.metadata.wasCached = true
          // 返回缓存的响应
          return Promise.reject({
            __cached: true,
            data: cachedData,
            config
          })
        }
        
        // 保存缓存键，用于响应拦截器
        config.metadata.cacheKey = cacheKey
        config.metadata.shouldCache = true
      }
    }
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    // 处理缓存响应
    if (response.__cached) {
      return Promise.resolve(response.data)
    }
    
    // 计算请求耗时
    let duration = 0
    if (response.config?.metadata?.startTime) {
      duration = new Date() - response.config.metadata.startTime
      if (duration > 3000) {
        safeLogger.warn(`慢请求警告: ${response.config.url} 耗时 ${duration}ms`)
      }
    }
    
    // 记录性能指标
    const wasCached = response.config?.metadata?.wasCached || false
    performanceMonitor.recordApiRequest(
      response.config.url,
      duration,
      wasCached
    )
    
    // 缓存响应数据（仅GET请求且配置了缓存）
    if (response.config?.metadata?.shouldCache && response.config?.metadata?.cacheKey) {
      requestCache.set(response.config.metadata.cacheKey, response.data)
    }
    
    // 如果是blob响应（文件下载），直接返回response对象
    if (response.config.responseType === 'blob') {
      return response.data
    }
    return response.data
  },
  async error => {
    // 处理缓存响应
    if (error.__cached) {
      // 记录缓存命中性能
      performanceMonitor.recordApiRequest(
        error.config.url,
        0, // 缓存响应时间几乎为0
        true
      )
      return Promise.resolve(error.data)
    }
    
    const config = error.config || {}
    
    // 记录错误信息
    const errorInfo = {
      url: config.url,
      method: config.method,
      status: error.response?.status,
      message: error.message,
      response: error.response?.data
    }
    
    safeLogger.error('API请求错误:', errorInfo)
    
    // 处理401未授权错误（Token过期或无效）
    if (error.response && error.response.status === 401) {
      // 排除注册和登录接口，这些接口的401错误不应该清除token
      const url = config.url || ''
      const isAuthEndpoint = url.includes('/users/register') || url.includes('/users/login')
      
      if (!isAuthEndpoint) {
        // 清除store中的登录状态
        if (store && store.dispatch) {
          store.dispatch('logout')
        } else if (typeof window !== 'undefined' && window.localStorage) {
          localStorage.removeItem('token')
        }
        
        // 显示提示信息（仅在浏览器环境中）
        if (typeof window !== 'undefined' && ElMessage) {
          ElMessage.warning('登录已过期，请重新登录')
        }
        
        // 如果不在登录/注册页面，跳转到登录页
        if (typeof window !== 'undefined' && window.location) {
          if (window.location.pathname !== '/login' && window.location.pathname !== '/register') {
            // 延迟跳转，避免在错误处理过程中立即跳转
            setTimeout(() => {
              window.location.href = '/login'
            }, 100)
          }
        }
      }
      return Promise.reject(error)
    }
    
    // 重试逻辑
    if (shouldRetry(error) && (!config.__retryCount || config.__retryCount < MAX_RETRIES)) {
      config.__retryCount = (config.__retryCount || 0) + 1
      
      // 指数退避延迟
      const delayTime = RETRY_DELAY * Math.pow(2, config.__retryCount - 1)
      
      safeLogger.info(`请求失败，${delayTime}ms后进行第${config.__retryCount}次重试:`, config.url)
      
      await delay(delayTime)
      return apiClient(config)
    }
    
    // 格式化错误消息
    let errorMessage = '请求失败'
    if (error.response) {
      const status = error.response.status
      const data = error.response.data
      
      if (data?.detail) {
        errorMessage = data.detail
      } else if (data?.error) {
        errorMessage = data.error
      } else if (data?.message) {
        errorMessage = data.message
      } else {
        switch (status) {
          case 400:
            errorMessage = '请求参数错误'
            break
          case 403:
            errorMessage = '没有权限执行此操作'
            break
          case 404:
            errorMessage = '请求的资源不存在'
            break
          case 500:
            errorMessage = '服务器内部错误'
            break
          case 502:
            errorMessage = '网关错误'
            break
          case 503:
            errorMessage = '服务暂时不可用'
            break
          case 504:
            errorMessage = '请求超时'
            break
          default:
            errorMessage = `请求失败 (${status})`
        }
      }
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置'
    } else {
      errorMessage = error.message || '请求失败'
    }
    
    // 存储错误消息到error对象，供调用方使用
    error.userMessage = errorMessage
    
    return Promise.reject(error)
  }
)

// 旅游相关API
class TravelAPI {
  /**
   * 规划路线
   * @param {Object} params - 路线规划参数
   * @param {number} params.budget - 预算
   * @param {number} params.start_attraction_id - 起始景点ID
   * @param {Array<number>} params.must_visit - 必访景点ID列表
   * @param {string} params.priority - 优先级（distance, cost, balanced）
   */
  static async planRoute(params) {
    try {
      const response = await apiClient.post('/api/routes/plan/', params)
      return response
    } catch (error) {
      safeLogger.error('路线规划失败:', error)
      throw error
    }
  }

  /**
   * 异步规划路线：返回 task_id
   * @param {Object} params - 路线规划参数
   */
  static async planRouteAsync(params) {
    try {
      const response = await apiClient.post('/api/routes/plan/async/', params)
      return response.data
    } catch (error) {
      safeLogger.error('异步规划失败:', error)
      throw error
    }
  }

  /**
   * 查询异步规划任务状态
   * @param {string} taskId - 任务ID
   */
  static async getRoutePlanStatus(taskId) {
    try {
      const response = await apiClient.get('/api/routes/plan/status/', { params: { task_id: taskId } })
      return response.data
    } catch (error) {
      safeLogger.error('查询规划任务状态失败:', error)
      throw error
    }
  }

  /**
   * 获取景点列表
   */
  static async getAttractions(params = {}) {
    try {
      const response = await apiClient.get('/api/attractions/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取景点列表失败:', error)
      throw error
    }
  }

  /**
   * 创建景点
   */
  static async createAttraction(attractionData) {
    try {
      const response = await apiClient.post('/api/attractions/', attractionData)
      return response
    } catch (error) {
      safeLogger.error('创建景点失败:', error)
      throw error
    }
  }

  /**
   * 更新景点
   */
  static async updateAttraction(attractionId, attractionData) {
    try {
      const response = await apiClient.put(`/api/attractions/${attractionId}/`, attractionData)
      return response
    } catch (error) {
      safeLogger.error('更新景点失败:', error)
      throw error
    }
  }

  /**
   * 删除景点
   */
  static async deleteAttraction(attractionId) {
    try {
      const response = await apiClient.delete(`/api/attractions/${attractionId}/`)
      return response
    } catch (error) {
      safeLogger.error('删除景点失败:', error)
      throw error
    }
  }

  /**
   * 搜索景点
   * @param {string} keyword - 搜索关键词
   */
  static async searchAttractions(keyword) {
    try {
      const response = await apiClient.get('/api/attractions/search/', {
        params: { keyword }
      })
      return response
    } catch (error) {
      safeLogger.error('搜索景点失败:', error)
      throw error
    }
  }

  /**
   * 获取景点详情
   * @param {number} attractionId - 景点ID
   * @returns {Promise<Object>} 景点详情对象
   */
  static async getAttractionDetail(attractionId) {
    try {
      const response = await apiClient.get(`/api/attractions/${attractionId}/`)
      // 响应拦截器已经返回了response.data，这里直接返回
      // 确保返回的是对象格式
      if (response && typeof response === 'object') {
        return response
      }
      // 如果返回的不是对象，尝试包装
      return response || {}
    } catch (error) {
      safeLogger.error('获取景点详情失败:', error)
      throw error
    }
  }

  /**
   * 获取景点图片列表
   * @param {number} attractionId - 景点ID
   * @returns {Promise<Array>} 图片列表
   */
  static async getAttractionImages(attractionId) {
    try {
      const response = await apiClient.get(`/api/attractions/${attractionId}/images/`)
      // 确保返回数组格式
      if (Array.isArray(response)) {
        return response
      }
      if (response && Array.isArray(response.data)) {
        return response.data
      }
      if (response && response.results && Array.isArray(response.results)) {
        return response.results
      }
      return []
    } catch (error) {
      safeLogger.error('获取景点图片失败:', error)
      // 不抛出错误，返回空数组，让调用方处理
      return []
    }
  }

  /**
   * 获取景点评价列表
   * @param {number} attractionId - 景点ID
   * @returns {Promise<Array>} 评价列表
   */
  static async getAttractionReviews(attractionId) {
    try {
      const response = await apiClient.get(`/api/attractions/${attractionId}/reviews/`)
      // 确保返回数组格式
      if (Array.isArray(response)) {
        return response
      }
      if (response && Array.isArray(response.data)) {
        return response.data
      }
      if (response && response.results && Array.isArray(response.results)) {
        return response.results
      }
      return []
    } catch (error) {
      safeLogger.error('获取景点评价失败:', error)
      // 不抛出错误，返回空数组，让调用方处理
      return []
    }
  }

  /**
   * 创建景点评价
   * @param {number} attractionId - 景点ID
   * @param {Object} reviewData - 评价数据 {rating, content}
   */
  static async createAttractionReview(attractionId, reviewData) {
    try {
      const response = await apiClient.post(`/api/attractions/${attractionId}/reviews/`, reviewData)
      return response
    } catch (error) {
      safeLogger.error('创建景点评价失败:', error)
      throw error
    }
  }

  /**
   * 收藏/取消收藏景点
   * @param {number} attractionId - 景点ID
   * @param {boolean} isFavorite - true为收藏，false为取消收藏
   */
  static async toggleFavorite(attractionId, isFavorite) {
    try {
      const method = isFavorite ? 'post' : 'delete'
      const response = await apiClient[method](`/api/attractions/${attractionId}/favorite/`)
      return response
    } catch (error) {
      safeLogger.error('收藏操作失败:', error)
      throw error
    }
  }

  /**
   * 获取用户收藏的景点列表
   */
  static async getFavoriteAttractions(params = {}) {
    try {
      const response = await apiClient.get('/api/attractions/favorites/', { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取收藏列表失败:', error)
      throw error
    }
  }

  /**
   * 收藏/取消收藏路线
   * @param {number} routeId - 路线ID
   * @param {boolean} isFavorite - true为收藏，false为取消收藏
   */
  static async toggleRouteFavorite(routeId, isFavorite) {
    try {
      const method = isFavorite ? 'post' : 'delete'
      const response = await apiClient[method](`/api/routes/history/${routeId}/favorite/`)
      return response
    } catch (error) {
      safeLogger.error('路线收藏操作失败:', error)
      throw error
    }
  }

  /**
   * 获取用户收藏的路线列表
   */
  static async getFavoriteRoutes(params = {}) {
    try {
      const response = await apiClient.get('/api/routes/history/favorites/', { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取收藏路线列表失败:', error)
      throw error
    }
  }

  /**
   * 获取路线规划历史
   */
  /**
   * 获取路线规划历史（支持分页）
   * @param {Object} params - 查询参数 { page, page_size }
   */
  static async getRouteHistory(params = {}) {
    try {
      const response = await apiClient.get('/api/routes/history/', { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取路线历史失败:', error)
      throw error
    }
  }

  /**
   * 分享路线
   * @param {number} routeId - 路线ID
   */
  static async shareRoute(routeId) {
    try {
      const response = await apiClient.post(`/api/routes/history/${routeId}/share/`)
      return response
    } catch (error) {
      safeLogger.error('分享路线失败:', error)
      throw error
    }
  }

  /**
   * 取消分享路线
   * @param {number} routeId - 路线ID
   */
  static async unshareRoute(routeId) {
    try {
      const response = await apiClient.post(`/api/routes/history/${routeId}/unshare/`)
      return response
    } catch (error) {
      safeLogger.error('取消分享失败:', error)
      throw error
    }
  }

  /**
   * 获取所有分享的路线
   */
  static async getSharedRoutes() {
    try {
      const response = await apiClient.get('/api/routes/history/shared/')
      return response
    } catch (error) {
      safeLogger.error('获取分享路线失败:', error)
      throw error
    }
  }

  /**
   * 获取推荐路线（热门路线）
   * @param {Object} params - 查询参数 {limit, category}
   */
  static async getRecommendedRoutes(params = {}) {
    try {
      const response = await apiClient.get('/api/routes/history/recommended/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取推荐路线失败:', error)
      throw error
    }
  }

  /**
   * 获取热门路线
   * @param {Object} params - 查询参数 {limit}
   */
  static async getHotRoutes(params = {}) {
    try {
      const response = await apiClient.get('/api/routes/history/hot/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取热门路线失败:', error)
      throw error
    }
  }

  /**
   * 获取景点排行榜
   * @param {Object} params - 查询参数 {type, category, period, limit}
   */
  static async getAttractionRankings(params = {}) {
    try {
      const response = await apiClient.get('/api/attractions/rankings/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取景点排行榜失败:', error)
      throw error
    }
  }

  /**
   * 通过分享码获取路线
   * @param {string} shareCode - 分享码
   */
  static async getRouteByShareCode(shareCode) {
    try {
      const response = await apiClient.get(`/api/routes/history/by-code/${shareCode}/`)
      return response.data
    } catch (error) {
      safeLogger.error('获取分享路线失败:', error)
      throw error
    }
  }

  /**
   * 增加路线使用次数
   * @param {number} routeId - 路线ID
   */
  static async incrementRouteUse(routeId) {
    try {
      const response = await apiClient.post(`/api/routes/history/${routeId}/increment_use/`)
      return response.data
    } catch (error) {
      safeLogger.error('增加使用次数失败:', error)
      throw error
    }
  }

  /**
   * 增加路线分享次数
   * @param {number} routeId - 路线ID
   */
  static async incrementRouteShare(routeId) {
    try {
      const response = await apiClient.post(`/api/routes/history/${routeId}/increment_share/`)
      return response.data
    } catch (error) {
      safeLogger.error('增加分享次数失败:', error)
      throw error
    }
  }

  /**
   * 获取系统统计数据
   */
  static async getAttractionStatistics() {
    try {
      const response = await apiClient.get('/api/attractions/statistics/')
      return response
    } catch (error) {
      safeLogger.error('获取统计数据失败:', error)
      throw error
    }
  }

  /**
   * 获取行程列表
   */
  static async getItineraries() {
    try {
      const response = await apiClient.get('/api/itineraries/')
      return response.data
    } catch (error) {
      safeLogger.error('获取行程列表失败:', error)
      throw error
    }
  }

  /**
   * 获取行程详情
   * @param {number} id - 行程ID
   */
  static async getItinerary(id) {
    try {
      const response = await apiClient.get(`/api/itineraries/${id}/`)
      return response
    } catch (error) {
      safeLogger.error('获取行程详情失败:', error)
      throw error
    }
  }

  /**
   * 创建行程
   * @param {Object} data - 行程数据
   */
  static async createItinerary(data) {
    try {
      const response = await apiClient.post('/api/itineraries/', data)
      return response
    } catch (error) {
      safeLogger.error('创建行程失败:', error)
      throw error
    }
  }

  /**
   * 更新行程
   * @param {number} id - 行程ID
   * @param {Object} data - 行程数据
   */
  static async updateItinerary(id, data) {
    try {
      const response = await apiClient.put(`/api/itineraries/${id}/`, data)
      return response
    } catch (error) {
      safeLogger.error('更新行程失败:', error)
      throw error
    }
  }

  /**
   * 删除行程
   * @param {number} id - 行程ID
   */
  static async deleteItinerary(id) {
    try {
      const response = await apiClient.delete(`/api/itineraries/${id}/`)
      return response
    } catch (error) {
      safeLogger.error('删除行程失败:', error)
      throw error
    }
  }

  /**
   * 添加活动到行程的某一天
   * @param {number} itineraryId - 行程ID
   * @param {number} dayId - 每日计划ID
   * @param {Object} activityData - 活动数据
   */
  static async addActivity(itineraryId, dayId, activityData) {
    try {
      const response = await apiClient.post(
        `/api/itineraries/${itineraryId}/days/${dayId}/activities/`,
        activityData
      )
      return response
    } catch (error) {
      safeLogger.error('添加活动失败:', error)
      throw error
    }
  }

  /**
   * 更新活动
   * @param {number} itineraryId - 行程ID
   * @param {number} dayId - 每日计划ID
   * @param {number} activityId - 活动ID
   * @param {Object} activityData - 活动数据
   */
  static async updateActivity(itineraryId, dayId, activityId, activityData) {
    try {
      const response = await apiClient.put(
        `/api/itineraries/${itineraryId}/days/${dayId}/activities/${activityId}/`,
        activityData
      )
      return response
    } catch (error) {
      safeLogger.error('更新活动失败:', error)
      throw error
    }
  }

  /**
   * 删除活动
   * @param {number} itineraryId - 行程ID
   * @param {number} dayId - 每日计划ID
   * @param {number} activityId - 活动ID
   */
  static async deleteActivity(itineraryId, dayId, activityId) {
    try {
      const response = await apiClient.delete(
        `/api/itineraries/${itineraryId}/days/${dayId}/activities/${activityId}/`
      )
      return response
    } catch (error) {
      safeLogger.error('删除活动失败:', error)
      throw error
    }
  }

  /**
   * 创建行程提醒
   * @param {number} itineraryId - 行程ID
   * @param {Object} reminderData - 提醒数据
   */
  static async createItineraryReminder(itineraryId, reminderData) {
    try {
      const response = await apiClient.post(`/api/itineraries/${itineraryId}/create_reminder/`, reminderData)
      return response
    } catch (error) {
      safeLogger.error('创建行程提醒失败:', error)
      throw error
    }
  }

  /**
   * 获取行程的所有提醒
   * @param {number} itineraryId - 行程ID
   */
  static async getItineraryReminders(itineraryId) {
    try {
      const response = await apiClient.get(`/api/itineraries/${itineraryId}/reminders/`)
      return response.data
    } catch (error) {
      safeLogger.error('获取行程提醒失败:', error)
      throw error
    }
  }

  /**
   * 获取即将到来的提醒（未来24小时内）
   */
  static async getUpcomingReminders() {
    try {
      const response = await apiClient.get('/api/itineraries/upcoming_reminders/')
      return response.data
    } catch (error) {
      safeLogger.error('获取即将到来的提醒失败:', error)
      throw error
    }
  }

  /**
   * 获取服务端通知列表（分页）
   * @param {Object} params - 分页与筛选参数
   */
  static async getNotifications(params = {}) {
    try {
      const response = await apiClient.get('/api/notifications/', { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取通知列表失败:', error)
      throw error
    }
  }

  /**
   * 标记通知为已读
   * @param {number} id - 通知ID
   */
  static async markNotificationRead(id) {
    try {
      const response = await apiClient.post(`/api/notifications/${id}/mark_read/`)
      return response.data
    } catch (error) {
      safeLogger.error('标记通知为已读失败:', error)
      throw error
    }
  }

  /**
   * 标记所有通知为已读
   */
  static async markAllNotificationsRead() {
    try {
      const response = await apiClient.post('/api/notifications/mark_all_read/')
      return response.data
    } catch (error) {
      safeLogger.error('标记所有通知为已读失败:', error)
      throw error
    }
  }

  /**
   * 清空服务器通知历史
   */
  static async clearNotifications() {
    try {
      const response = await apiClient.post('/api/notifications/clear/')
      return response.data
    } catch (error) {
      safeLogger.error('清空通知历史失败:', error)
      throw error
    }
  }

  /**
   * 启用/禁用提醒
   * @param {number} reminderId - 提醒ID
   */
  static async toggleReminder(reminderId) {
    try {
      const response = await apiClient.post(`/api/itineraries/reminders/${reminderId}/toggle/`)
      return response
    } catch (error) {
      safeLogger.error('切换提醒状态失败:', error)
      throw error
    }
  }

  /**
   * 删除提醒
   * @param {number} reminderId - 提醒ID
   */
  static async deleteReminder(reminderId) {
    try {
      const response = await apiClient.delete(`/api/itineraries/reminders/${reminderId}/`)
      return response
    } catch (error) {
      safeLogger.error('删除提醒失败:', error)
      throw error
    }
  }

  /**
   * 用户注册
   */
  static async register(userData) {
    try {
      const response = await apiClient.post('/api/users/auth/register/', userData)
      return response
    } catch (error) {
      safeLogger.error('注册失败:', error)
      throw error
    }
  }

  /**
   * 用户登录
   */
  static async login(credentials) {
    try {
      const response = await apiClient.post('/api/users/auth/login/', credentials)
      return response
    } catch (error) {
      safeLogger.error('登录失败:', error)
      throw error
    }
  }

  /**
   * 获取当前用户信息
   */
  static async getCurrentUser() {
    try {
      const response = await apiClient.get('/api/users/me/')
      return response.data
    } catch (error) {
      safeLogger.error('获取用户信息失败:', error)
      throw error
    }
  }

  /**
   * 更新用户偏好
   */
  static async updatePreferences(userId, preferences) {
    try {
      const response = await apiClient.put(`/api/users/${userId}/preferences/`, { preferences })
      return response
    } catch (error) {
      safeLogger.error('更新偏好失败:', error)
      throw error
    }
  }

  /**
   * 关注用户
   */
  static async followUser(userId) {
    try {
      const response = await apiClient.post(`/api/users/${userId}/follow/`)
      return response
    } catch (error) {
      safeLogger.error('关注失败:', error)
      throw error
    }
  }

  /**
   * 取消关注用户
   */
  static async unfollowUser(userId) {
    try {
      const response = await apiClient.delete(`/api/users/${userId}/follow/`)
      return response
    } catch (error) {
      safeLogger.error('取消关注失败:', error)
      throw error
    }
  }

  /**
   * 获取推荐景点
   */
  static async getRecommendations(params = {}) {
    try {
      const response = await apiClient.get('/api/attractions/recommendations/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取推荐失败:', error)
      throw error
    }
  }

  /**
   * 发布动态
   */
  static async createPost(postData) {
    try {
      const response = await apiClient.post('/api/social/posts/', postData)
      return response.data || response
    } catch (error) {
      safeLogger.error('发布动态失败:', error)
      throw error
    }
  }

  /**
   * 获取动态列表
   */
  static async getPosts() {
    try {
      const response = await apiClient.get('/api/social/posts/')
      return response.data
    } catch (error) {
      safeLogger.error('获取动态列表失败:', error)
      throw error
    }
  }

  /**
   * 更新动态
   * @param {number} postId - 动态ID
   * @param {object} postData - 动态数据
   */
  static async updatePost(postId, postData) {
    try {
      const response = await apiClient.put(`/api/social/posts/${postId}/`, postData)
      return response.data
    } catch (error) {
      safeLogger.error('更新动态失败:', error)
      throw error
    }
  }

  /**
   * 删除动态
   * @param {number} postId - 动态ID
   */
  static async deletePost(postId) {
    try {
      const response = await apiClient.delete(`/api/social/posts/${postId}/`)
      return response || {}
    } catch (error) {
      safeLogger.error('删除动态失败:', error)
      throw error
    }
  }

  /**
   * 点赞动态
   */
  static async likePost(postId) {
    try {
      const response = await apiClient.post(`/api/social/posts/${postId}/like/`)
      return response
    } catch (error) {
      safeLogger.error('点赞失败:', error)
      throw error
    }
  }

  /**
   * 取消点赞
   */
  static async unlikePost(postId) {
    try {
      const response = await apiClient.delete(`/api/social/posts/${postId}/like/`)
      return response
    } catch (error) {
      safeLogger.error('取消点赞失败:', error)
      throw error
    }
  }

  /**
   * 添加评论
   */
  static async addComment(postId, content) {
    try {
      const response = await apiClient.post(`/api/social/posts/${postId}/comment/`, { content })
      return response
    } catch (error) {
      safeLogger.error('添加评论失败:', error)
      throw error
    }
  }

  // ==================== 管理员API ====================

  /**
   * 获取用户列表（管理员）
   */
  static async getAdminUsers(params = {}) {
    try {
      const response = await apiClient.get('/api/users/admin/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取用户列表失败:', error)
      throw error
    }
  }

  /**
   * 切换用户状态（启用/禁用）
   */
  static async toggleUserActive(userId) {
    try {
      const response = await apiClient.post(`/api/users/admin/${userId}/toggle_active/`)
      return response
    } catch (error) {
      safeLogger.error('切换用户状态失败:', error)
      throw error
    }
  }

  /**
   * 删除用户（管理员）
   */
  static async deleteAdminUser(userId) {
    try {
      const response = await apiClient.delete(`/api/users/admin/${userId}/delete/`)
      return response
    } catch (error) {
      safeLogger.error('删除用户失败:', error)
      throw error
    }
  }

  /**
   * 获取用户统计（管理员）
   */
  static async getUserStatistics() {
    try {
      const response = await apiClient.get('/api/users/admin/statistics/')
      return response
    } catch (error) {
      safeLogger.error('获取用户统计失败:', error)
      throw error
    }
  }

  /**
   * 获取动态列表（管理员）
   */
  static async getAdminPosts(params = {}) {
    try {
      const response = await apiClient.get('/api/social/admin/posts/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取动态列表失败:', error)
      throw error
    }
  }

  /**
   * 导出数据
   * @param {string} type - 数据类型（attractions, users, posts, routes）
   * @param {string} format - 导出格式（excel, csv）
   */
  static async exportData(type, format = 'csv') {
    try {
      const response = await apiClient.post('/api/users/admin/export/export_data/', {
        type,
        format
      }, {
        responseType: 'blob'  // 重要：设置响应类型为blob以处理文件下载
      })
      return response
    } catch (error) {
      safeLogger.error('导出数据失败:', error)
      throw error
    }
  }

  /**
   * 删除动态（管理员）
   */
  static async deleteAdminPost(postId) {
    try {
      const response = await apiClient.delete(`/api/social/admin/posts/${postId}/delete/`)
      return response
    } catch (error) {
      safeLogger.error('删除动态失败:', error)
      throw error
    }
  }

  /**
   * 获取动态统计（管理员）
   */
  static async getPostStatistics() {
    try {
      const response = await apiClient.get('/api/social/admin/posts/statistics/')
      return response
    } catch (error) {
      safeLogger.error('获取动态统计失败:', error)
      throw error
    }
  }

  /**
   * 获取评论列表（管理员）
   */
  static async getAdminComments(params = {}) {
    try {
      const response = await apiClient.get('/api/social/admin/comments/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取评论列表失败:', error)
      throw error
    }
  }

  /**
   * 删除评论（管理员）
   */
  static async deleteAdminComment(commentId) {
    try {
      const response = await apiClient.delete(`/api/social/admin/comments/${commentId}/delete/`)
      return response
    } catch (error) {
      safeLogger.error('删除评论失败:', error)
      throw error
    }
  }

  /**
   * 获取评论统计（管理员）
   */
  static async getCommentStatistics() {
    try {
      const response = await apiClient.get('/api/social/admin/comments/statistics/')
      return response
    } catch (error) {
      safeLogger.error('获取评论统计失败:', error)
      throw error
    }
  }

  /**
   * 获取操作日志列表（管理员）
   */
  static async getAdminLogs(params = {}) {
    try {
      const response = await apiClient.get('/api/users/admin/logs/', { params })
      return response
    } catch (error) {
      safeLogger.error('获取操作日志失败:', error)
      throw error
    }
  }

  /**
   * 获取操作日志统计（管理员）
   */
  static async getLogStatistics() {
    try {
      const response = await apiClient.get('/api/users/admin/logs/statistics/')
      return response
    } catch (error) {
      safeLogger.error('获取操作日志统计失败:', error)
      throw error
    }
  }

  /**
   * 获取系统健康检查信息
   */
  static async getHealthCheck() {
    try {
      const response = await apiClient.get('/api/users/admin/health/health/')
      return response
    } catch (error) {
      safeLogger.error('获取健康检查失败:', error)
      throw error
    }
  }

  /**
   * 获取用户主页信息（包含统计信息）
   * @param {number} userId - 用户ID
   */
  static async getUserProfile(userId) {
    try {
      const response = await apiClient.get(`/api/users/${userId}/profile/`)
      return response
    } catch (error) {
      safeLogger.error('获取用户主页信息失败:', error)
      throw error
    }
  }

  /**
   * 获取用户的动态列表
   * @param {number} userId - 用户ID
   * @param {Object} params - 查询参数（page, page_size等）
   */
  static async getUserPosts(userId, params = {}) {
    try {
      const response = await apiClient.get(`/api/users/${userId}/posts/`, { params })
      return response
    } catch (error) {
      safeLogger.error('获取用户动态列表失败:', error)
      throw error
    }
  }

  /**
   * 获取用户的收藏列表（景点和路线）
   * @param {number} userId - 用户ID
   */
  static async getUserFavorites(userId) {
    try {
      const response = await apiClient.get(`/api/users/${userId}/favorites/`)
      return response
    } catch (error) {
      safeLogger.error('获取用户收藏列表失败:', error)
      throw error
    }
  }

  /**
   * 获取动态列表（支持按用户筛选）
   * @param {Object} params - 查询参数（user_id, page, page_size等）
   */
  static async getPostsWithParams(params = {}) {
    try {
      const response = await apiClient.get('/api/social/posts/', { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取动态列表失败:', error)
      throw error
    }
  }

  /**
   * 获取帖子评论（支持分页）
   * @param {number} postId - 动态ID
   * @param {Object} params - 分页参数 { page, page_size }
   */
  static async getPostComments(postId, params = {}) {
    try {
      const response = await apiClient.get(`/api/social/posts/${postId}/comments/`, { params })
      return response.data
    } catch (error) {
      safeLogger.error('获取评论列表失败:', error)
      throw error
    }
  }

  /**
   * 发送邮箱验证码
   * @param {string} email - 邮箱地址
   */
  static async sendEmailVerification(email) {
    try {
      const response = await apiClient.post('/api/users/send_email_verification/', { email })
      return response.data
    } catch (error) {
      safeLogger.error('发送邮箱验证码失败:', error)
      throw error
    }
  }

  /**
   * 验证邮箱
   * @param {string} email - 邮箱地址
   * @param {string} verificationCode - 验证码
   */
  static async verifyEmail(email, verificationCode) {
    try {
      const response = await apiClient.post('/api/users/verify_email/', {
        email,
        verification_code: verificationCode
      })
      return response.data
    } catch (error) {
      safeLogger.error('验证邮箱失败:', error)
      throw error
    }
  }

  /**
   * 发送手机验证码
   * @param {string} phone - 手机号
   */
  static async sendPhoneVerification(phone) {
    try {
      const response = await apiClient.post('/api/users/send_phone_verification/', { phone })
      return response.data
    } catch (error) {
      safeLogger.error('发送手机验证码失败:', error)
      throw error
    }
  }

  /**
   * 验证手机号
   * @param {string} phone - 手机号
   * @param {string} verificationCode - 验证码
   */
  static async verifyPhone(phone, verificationCode) {
    try {
      const response = await apiClient.post('/api/users/verify_phone/', {
        phone,
        verification_code: verificationCode
      })
      return response.data
    } catch (error) {
      safeLogger.error('验证手机号失败:', error)
      throw error
    }
  }
}

export default TravelAPI

